package user

import (
	"crypto/sha256"
	"fmt"
	"goProject/cfg"
	"goProject/db"
	"io"
	"net/http"
	"os"
	"path"

	"gitee.com/ruige_fun/util/rlog"
	"gitee.com/ruige_fun/util/std"
	"github.com/kataras/iris/v12"
)

func uploadFile(c iris.Context) {
	file, _, err := c.FormFile("file")
	if err != nil {
		c.StatusCode(http.StatusBadRequest)
		c.JSON(std.NewResp(http.StatusBadRequest, "未读取到file", nil, nil))
		return
	}
	uploadPath, _ := db.RunConfig.Get(db.PublicDirKeyUpload)
	if uploadPath == "" {
		c.StatusCode(http.StatusInternalServerError)
		c.JSON(std.NewResp(http.StatusInternalServerError, "服务器出错，请稍后上传：管理员未设置上传路径", nil, nil))
		return
	}
	all, err := io.ReadAll(file)
	if err != nil {
		c.StatusCode(http.StatusInternalServerError)
		c.JSON(std.NewResp(http.StatusInternalServerError, fmt.Sprint("服务器出错，请稍后上传：", err), nil, nil))
		return
	}
	sha256hex := fmt.Sprintf("%x", sha256.Sum256(all))
	err = os.WriteFile(path.Join(uploadPath, sha256hex), all, cfg.DefaultFileModel)
	if err != nil {
		c.StatusCode(http.StatusInternalServerError)
		c.JSON(std.NewResp(http.StatusInternalServerError, fmt.Sprint("服务器出错，请稍后上传：", err), nil, nil))
		return
	}
	c.JSON(std.NewResp(http.StatusOK, "", sha256hex, nil))
	rlog.Info(c.GetID(), c.RemoteAddr(), "上传了文件：", path.Join(uploadPath, sha256hex))
}
